package com.passioneffect.manager {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	import com.passioneffect.collection.Collection;
	import com.passioneffect.collection.Iterator;	

	/**
	 * @author Passion Effect
	 */
	public class LoaderManager extends EventDispatcher {

		private var bitmaps : Dictionary;
		private var waitingList : Dictionary;
		
		public function LoaderManager() {
			bitmaps = new Dictionary(true);
			waitingList = new Dictionary(true);
		}

		public function getBitmap(url : String) : Bitmap {
			var bitmapData:BitmapData=BitmapData(bitmaps[url]);
			var bitmap : Bitmap;
			
			if(bitmapData) {
				bitmap = new Bitmap(bitmapData);
			}else {
				bitmap = new Bitmap();
				var loader : Loader = new Loader();
				var info:LoaderInfo=loader.contentLoaderInfo;
				
				info.addEventListener(Event.COMPLETE, completeHandler);
				waitingList[info] = {bitmap:bitmap,url:url};
				loader.load(new URLRequest(url));
				
			}
			return bitmap;
		}

		private function completeHandler(evt : Event) : void {
			
			var info : LoaderInfo = LoaderInfo(evt.currentTarget);
			var obj:Object=waitingList[info];
			
			var bitmap : Bitmap = obj.bitmap;
			var url:String=obj.url;
			
			var bitmapData : BitmapData = new BitmapData(info.width, info.height, true, 0x000000);
			
			bitmapData.draw(info.content);
			
			bitmaps[url]=bitmapData;
			bitmap.bitmapData = bitmapData;
			
			waitingList[info] = null;
			info.loader.removeEventListener(Event.COMPLETE, completeHandler);
			
		}

	}
}
